<!--
 * @file 添加、编辑表单
 * @author its-wild(https://gitee.com/its-wild)
 * @date 2021/12/03
-->
<template>
	<a-modal v-bind="$attrs" :title="title" :ok-button-props="{loading: loading}" :is-edit="isEdit" @ok="onSubmit">
		<a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
			<a-form-item ref="name" label="姓名" name="name">
				<a-input v-model:value="formState.name" placeholder="请输入名字" />
			</a-form-item>
			<a-form-item label="角色" name="type">
				<a-select v-model:value="formState.type" placeholder="请选择角色">
					<a-select-option value="1">校长</a-select-option>
					<a-select-option value="2">教务</a-select-option>
					<a-select-option value="3">教师</a-select-option>
					<a-select-option value="4">保密</a-select-option>
				</a-select>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script lang="ts">
	import {defineComponent, ref, reactive, UnwrapRef, toRaw, computed} from 'vue'
	import pick from 'lodash.pick'
	import {isUndefinedEmptyNull} from '@/utils'
	import {post} from '@/utils/axios'
	import {exampleApis} from '@/apis'

	interface FormState {
		name: string | undefined
		type: string | undefined
	}

	export default defineComponent({
		name: 'EditForm',
		props: {
			model: {
				type: Object,
			},
		},
		setup(props, {emit, attrs}) {
			const title = ref('添加')
			const loading = ref(false)
			const setLoading = (val: boolean) => {
				loading.value = val
			}
			// 表单
			const formRef = ref()
			const formState: UnwrapRef<FormState> = reactive({
				name: undefined,
				type: undefined,
			})
			const rules = {
				name: [
					{required: true, message: '请输入名字', trigger: 'blur'},
					{min: 2, max: 10, message: '长度2到10', trigger: 'blur'},
				],
				type: [{required: true, message: '请选择角色', trigger: 'change'}],
			}
			const resetForm = () => {
				formRef.value.resetFields()
			}

			// 编辑
			const isEdit = computed(() => {
				const model = props.model
				const id = model?.id
				if (attrs.visible && id) {
					const keyArr = ['name', 'type']
					const record = pick(model, keyArr)
					keyArr.forEach((key) => {
						if (!isUndefinedEmptyNull(record[key])) {
							(formState as any)[key] = record[key]
						}
					})
				}

				return !!id
			})

			const onSubmit = () => {
				formRef.value
					.validate()
					.then(async () => {
						let url = exampleApis.add
						// 校验通过，请求后台接口
						if (props?.model?.id) {
							url = exampleApis.edit
						}
						const params = {
							...props?.model,
							...toRaw(formState),
						}
						setLoading(true)
						await post(url, params)
						resetForm()
						setLoading(false)
						emit('sure')
					})
					.catch((error: any) => {
						console.log('error', error)
					})
			}

			return {
				title,
				loading,
				setLoading,
				formRef,
				labelCol: {span: 6},
				wrapperCol: {span: 14},
				isEdit,
				formState,
				rules,
				onSubmit,
			}
		},
	})
</script>

<style scoped lang="less"></style>
